﻿Imports DotNetNuke.Services.Localization
Imports DotNetNuke.Services.Exceptions
Imports DotNetNuke.Common
Imports DotNetNuke.Common.Utilities
Imports System.Text.RegularExpressions

Namespace effority.WF_HTML

    Partial Class WF_ControlCenter
        Inherits WF_HTML_Base

#Region " Event Handlers "

        Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

            Try

                ' hier sollte noch eine zusätzliche Rechteabfrage eingefügt werden

                wf.ModuleId = Me.ModuleId
                wf.UserLevel = UserLevelEnum.Workflow

                Dim objText As HtmlTextInfo

                If Not IsPostBack Then

                    Dim cont As New effority.WF_HTML.HtmlTextController

                    objText = cont.GetHtmlTextLastVersion(Me.ModuleId)

                    If Not objText Is Nothing Then
                        Me.BindId(objText.Id)
                    Else
                        Me.BindId(DotNetNuke.Common.Utilities.Null.NullInteger)
                    End If

                    hpBack.NavigateUrl = NavigateURL(TabId)

                End If

            Catch ex As Exception

                ProcessModuleLoadException(Me.Page, ex)

            End Try


        End Sub

        Private Sub wf_ActiveVersionChanged(ByVal sender As Object, ByVal e As Integer) Handles wf.ActiveVersionChanged

            Try

                Dim cont As New HtmlTextController

                cont.SetHtmlTextActive(e)

                Me.BindId(e)

            Catch exc As Exception

                ProcessModuleLoadException(Me, exc)

            End Try

        End Sub

        Private Sub wf_ViewVersion(ByVal sender As Object, ByVal e As Integer) Handles wf.ViewVersion

            Try

                Dim cont As New HtmlTextController

                Me.BindId(e)

            Catch exc As Exception

                ProcessModuleLoadException(Me, exc)

            End Try

        End Sub

        Private Sub wf_DeleteVersion(ByVal sender As Object, ByVal e As Integer) Handles wf.DeleteVersion

            Try

                Dim cont As New HtmlTextController

                cont.DeleteHtmlText(e)

                ' keinen neuen Text binden

            Catch exc As Exception

                ProcessModuleLoadException(Me, exc)

            End Try


        End Sub

#End Region

#Region " Private Methods "

        Private Sub BindId(ByVal Id As Int32)

            Dim objHTML As New HtmlTextController
            Dim objText As HtmlTextInfo

            objText = objHTML.GetHtmlTextById(Id)

            Dim strContent As String

            ' get html
            If Not objText Is Nothing Then
                strContent = Server.HtmlDecode(CType(objText.DeskTopHTML, String))

                ' handle Smart Tags that might have been used
                strContent = ProcessTags(strContent)

                'add content to module
                ' lblContent.Controls.Add(New LiteralControl(ManageUploadDirectory(strContent, PortalSettings.HomeDirectory)))
                lblText.Text = ManageUploadDirectory(strContent, PortalSettings.HomeDirectory)

            End If


        End Sub

        'Local tag cache to avoid multiple generations of the same tag
        Private tagCache As Hashtable

        ''' -----------------------------------------------------------------------------
        ''' <summary>
        ''' ManageUploadDirectory ensures that all image refs are to the correct directory
        ''' </summary>
        ''' <remarks>
        ''' </remarks>
        ''' <history>
        ''' </history>
        ''' -----------------------------------------------------------------------------
        Private Function ManageUploadDirectory(ByVal strHTML As String, ByVal strUploadDirectory As String) As String

            Dim P As Integer

            P = InStr(1, strHTML.ToLower, "src=""")
            While P <> 0
                ManageUploadDirectory = ManageUploadDirectory & Left(strHTML, P + 4)

                strHTML = Mid(strHTML, P + 5)

                ' add uploaddirectory if we are linking internally
                Dim strSRC As String = Left(strHTML, InStr(1, strHTML, """") - 1)
                If InStr(1, strSRC, "://") = 0 And Left(strSRC, 1) <> "/" And strSRC.IndexOf(strUploadDirectory.Substring(strUploadDirectory.IndexOf("Portals/"))) = -1 Then

                    strHTML = strUploadDirectory & strHTML
                End If

                P = InStr(1, strHTML.ToLower, "src=""")
            End While

            ManageUploadDirectory = ManageUploadDirectory & strHTML

        End Function

        ''' -----------------------------------------------------------------------------
        ''' <summary>
        ''' Replaces all smart Tags in content with their appropriate values.
        ''' </summary>
        ''' <param name="content"></param>
        ''' <returns>Content with replaced Tags</returns>
        ''' <remarks>
        ''' </remarks>
        ''' <history>
        ''' </history>
        ''' -----------------------------------------------------------------------------

        Private Function ProcessTags(ByVal content As String) As String
            Dim retval As New System.Text.StringBuilder

            Dim position As Integer = 0

            'Find all tags used in text
            'The regular expression matches the tag including the square brackets:
            'in "aaa[bbb[ccc]ddd]eee" it matches only "[ccc]"
            For Each _match As Match In Regex.Matches(content, "\[([^\[]*?)\]")
                'Append the text before the match to the result
                retval.Append(content.Substring(position, _match.Index - position))

                'Process the tag and append the output to the result
                retval.Append(ProcessTag(_match.Value))

                'Set the starting point for the next match
                position = _match.Index + _match.Value.Length

            Next

            'Append the rest of the text to the result
            retval.Append(content.Substring(position))

            Return retval.ToString
        End Function

        ''' -----------------------------------------------------------------------------
        ''' <summary>
        ''' Processes all occurrences of the given tag by the given value in given content
        ''' </summary>
        ''' <param name="tag"></param>
        ''' <returns>Content with replaced Tag</returns>
        ''' <remarks>
        ''' A hashtable is used to make sure each tag will only be processed once each load.
        ''' </remarks>
        ''' <history>
        ''' </history>
        ''' -----------------------------------------------------------------------------
        Private Function ProcessTag(ByVal tag As String) As String

            'Store the tag in the result to keep the text if its not a smarttag
            Dim retval As String = tag
            Dim tagitems As String() = tag.Substring(1, tag.Length - 2).Trim().Split(" ".ToCharArray())
            'Ensure case independency
            tagitems(0) = tagitems(0).ToUpper()
            'Initialize cache if not created
            If tagCache Is Nothing Then tagCache = New Hashtable
            'If we have tag in cache, simply return the cached content
            If tagCache.ContainsKey(tag) Then
                retval = tagCache(tag).ToString()
            Else
                'Build tag content value if its a known tag
                Select Case tagitems(0)
                    Case "PORTAL.NAME"
                        retval = PortalSettings.PortalName
                        tagCache(tag) = retval
                    Case "DATE"
                        If tagitems.Length = 2 Then
                            Try
                                retval = DateTime.Now.ToString(tagitems(1))
                            Catch
                                retval = DateTime.Now.ToShortDateString()
                            End Try
                        Else
                            retval = DateTime.Now.ToShortDateString()
                        End If
                        tagCache(tag) = retval
                    Case "TIME"
                        If tagitems.Length = 2 Then
                            Try
                                retval = DateTime.Now.ToString(tagitems(1))
                            Catch
                                retval = DateTime.Now.ToShortTimeString()
                            End Try
                        Else
                            retval = DateTime.Now.ToShortTimeString()
                        End If
                        tagCache(tag) = retval
                End Select
            End If

            Return retval
        End Function

#End Region

    End Class

End Namespace